import express, { Request, Response } from "express"
import { checkAppToken, checkError } from "../../utils/token"
import { LoggedInRequest } from "../../types"
import { ShoppingCar_AddType ,SHListQueryType, SHChangeNumType, SHCancelParmaType} from "@Tea/model"
import { useCheckAndResponse } from "../../utils/common"
import { ShoppingCarCtx } from "../../context/ShoppingCarCtx"

const shoppingCarRouter = express.Router()

/**
 * 添加时先查询列表中是否有该商品的订单
 * 如果有的话，在该条数据的数量加 1
 * 没有就直接插入
 */
shoppingCarRouter.post('/addCommodity', checkAppToken, async (req: LoggedInRequest, res: Response) => { 
  try {
    const params = req.body as ShoppingCar_AddType
    const data = await ShoppingCarCtx.getInstance().shoppingCarList({
      teaId: params.teaId
    }, req.userInfo.userId)

    if (data.length) {
      const changeResult = await ShoppingCarCtx.getInstance().changeNumber({
        shoppingId: data[0].shoppingId, orderNumber: data[0].orderNumber + 1
      }, req.userInfo.userId)

      return useCheckAndResponse(res, changeResult[0], '购物车中已存在，该物品的数量已为您加1')
    }

    const addResult = await ShoppingCarCtx.getInstance().addCommodity(params.teaId, req.userInfo.userId)
    useCheckAndResponse(res, addResult[0], '新增成功')
  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

shoppingCarRouter.post('/cancelCommodity', checkAppToken, async (req: LoggedInRequest, res: Response) => { 
  try {
    const params = req.body as SHCancelParmaType
    if (!params.shoppingIds?.length) {
      return res.send({
        code: 0,
        msg:"请求参数错误"
      })
    }
    const addResult = await ShoppingCarCtx.getInstance().cancelCommodity(params, req.userInfo.userId)
    useCheckAndResponse(res, addResult[0], '删除成功')
  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

shoppingCarRouter.put('/changeNumber', checkAppToken, async (req: LoggedInRequest, res: Response) => { 
  try {
    const params = req.body as SHChangeNumType
    const result = await ShoppingCarCtx.getInstance().changeNumber(params, req.userInfo.userId)
    
    const affect = result[0].affectedRows

    res.send({
      code: Number(!!affect),
      msg: affect ? "购物车数量修改成功" : "购物车中不存在该商品"
    })

  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

/**
 * @use 获取购物车的列表
 * @query {} teaId 可选参数
 * @query {} teaName 可选参数
 */
shoppingCarRouter.get('/shoppingCarList', async (req: LoggedInRequest, res: Response) => {
  try {
    const query = req.query as any as SHListQueryType
    const data = await ShoppingCarCtx.getInstance().shoppingCarList(query, req.userInfo.userId)
  
    setTimeout(() => {
      res.send({
        code: 1,
        msg: '查询成功',
        data
      })
    }, Math.random() * 1000)
  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg:checkError(ex)
    })
  }
})

export default shoppingCarRouter